RT

您所在的位置:网站首页 esp32 rtthread RT

RT

#RT| 来源: 网络整理| 查看: 265

RS232和RS485串口

对于我来收,RS232和485的区别目前来说并不是很大,因为只用到了数据的收发,对于大项目的作用,RS485用的比较多。 RT-Thread的比Keil好用多了,这两者的概念我不清楚,比如我只是认为Keil只是用来编辑、编译、烧录、调试的工具(调试用的比较少)。Keil使用一个CPIO口需要对这个口初始化、使能、模式等一系列操作,但是RT-Thread不一样

/* 设置LED引脚为输出模式 */ rt_pin_mode(136, PIN_MODE_OUTPUT);

这样就方便很多,但是终究还是需要学习底层的。 直接开始吧 写代码之前,想想如何完成串口数据收发。

寻找串口(使能,初始化,设置波特率)发送数据给串口、串口接收中断(收到数据后下一步的操作)发送同样的数据给PC 寻找串口

定义串口名字

#define UART1_NAME "uart1" /* 串口设备句柄 */ static rt_device_t serial; /* 串口初始化默认参数 */ struct serial_configure config = RT_SERIAL_CONFIG_DEFAULT;

查找串口

char uart_name[RT_NAME_MAX]; /* 定义一个uart_name,用于寻找串口 */ rt_strncpy(uart_name, UART3_NAME, RT_NAME_MAX); /* 查找系统中的串口设备 */ serial = rt_device_find(uart_name); if (!serial) { rt_kprintf("find %s failed!\n", uart_name); return RT_ERROR; }

打开串口,定义接收回调函数

/* 以中断接收及轮询发送模式打开串口设备 */ rt_device_open(serial, RT_DEVICE_FLAG_INT_RX); /* 设置接收回调函数 */ rt_device_set_rx_indicate(serial, uart_input);

发送一个数据,使串口触发中断

char str[] = "hello"; /* 发送字符串 */ rt_device_write(serial, 0, str, sizeof(str));

触发中断

rt_err_t uart_input(rt_device_t dev, rt_size_t size) { /* 串口接收到数据后产生中断,调用此回调函数 */ char ch; /*设置LED引脚为输出模式,默认高电平*/ rt_pin_mode(136, PIN_MODE_OUTPUT); rt_pin_write(136, PIN_HIGH); while (rt_device_read(dev, 0, &ch, 1) == 0) ; if(ch == 's') { rt_pin_write(136, PIN_LOW); } else if(ch == 'p') { rt_pin_write(136, PIN_HIGH); } rt_device_write(dev, 0, &ch, 1); return RT_EOK; }

中断函数把接收到的字符重新读取,再发送到PC端。 目前似乎只支持一个字符,待过一天再进行升级。

代码,具体调用可直接添加到main.c文件后再修改一点 #include #include #include "uart1.h" #include #include #define UART1_NAME "uart1" static rt_device_t serial; /* 初始化配置参数 */ struct serial_configure config = RT_SERIAL_CONFIG_DEFAULT; /* 接收数据回调函数 */ rt_err_t uart_input(rt_device_t dev, rt_size_t size) { /* 串口接收到数据后产生中断,调用此回调函数 */ char ch; /*设置LED引脚为输出模式,默认高电平*/ rt_pin_mode(136, PIN_MODE_OUTPUT); rt_pin_write(136, PIN_HIGH); while (rt_device_read(dev, 0, &ch, 1) == 0) ; if(ch == 's') { rt_pin_write(136, PIN_LOW); } else if(ch == 'p') { rt_pin_write(136, PIN_HIGH); } rt_device_write(dev, 0, &ch, 1); /*发送完数据,将RE#引脚设置低电平,串口为输入模式*/ rt_pin_write(44, PIN_LOW); return RT_EOK; } int uart_sample(void) { rt_err_t ret = RT_EOK; char uart_name[RT_NAME_MAX]; char str[] = "hello"; rt_strncpy(uart_name, UART3_NAME, RT_NAME_MAX); /* 查找系统中的串口设备 */ serial = rt_device_find(uart_name); if (!serial) { rt_kprintf("find %s failed!\n", uart_name); return RT_ERROR; } /* 以中断接收及轮询发送模式打开串口设备 */ rt_device_open(serial, RT_DEVICE_FLAG_INT_RX); /* 设置接收回调函数 */ rt_device_set_rx_indicate(serial, uart_input); /* 发送字符串 */ rt_device_write(serial, 0, str, sizeof(str)); return ret; }


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3